<template>
  <div id="Page" v-skeleton="isPageLoad" class="page page-goods-detail">
    <!--顶部属性类别-->
    <div id="HeadTop" class="head-top-tab">
      <template v-if="!goodsVideo.playing">
        <div @click="topScrollAttr('')" class="item-row "><p :class="{'is-selected':topAttrName===''}">商品</p></div>
        <div @click="topScrollAttr('Details')" class="item-row"><p :class="{'is-selected':topAttrName==='Details'}">
          详情</p></div>
        <div @click="topScrollAttr('Evaluation')" class="item-row"><p
          :class="{'is-selected':topAttrName==='Evaluation'}">评论</p></div>
        <div @click="back" class="back-icon"><i class="iconfont icon-arrow-left"></i></div>
      </template>
      <i v-else @click="playVideo(0)" class="iconfont icon-guanbi"></i>
    </div>
    <!--商品 幻灯片-->
    <div id="HeadSwiper" class="goods-swiper">
      <div v-if="goodsVideo.url && goodsVideo.playing" class="player-container">
        <video id="GoodsVideo"
               v-cloak
               webkit-playsinline="true"
               :class="['player']"
               :src="goodsVideo.url"
               @ended="playVideo(0)"></video>
      </div>
      <van-swipe v-show="!goodsVideo.playing" class="van-swipe-container" @change="index=>headSwipeIndex = index">
        <van-swipe-item
          :key="item.id"
          v-for="item in goods.productPicList">
          <div @click.stop="openPreviewProduct(item.picUrl)" class="swipe-row">
            <img v-lazy="item.picUrl">
            <i v-if="item.videoUrl" @click.stop="playVideo(1,item)" class="iconfont icon-bofang"></i>
          </div>
        </van-swipe-item>
        <div class="custom-indicator" slot="indicator">
          {{ headSwipeIndex + 1 }}/{{goods.productPicList.length}}
        </div>
      </van-swipe>
    </div>
    <!--商品描述-->
    <div class="introduction">
      <p class="price-info">&#165; <span class="size">{{goods.price}}</span></p>
      <p class="name">{{goods.productDesc}}</p>
      <p class="goods-no">货号：{{goods.goodsNo}}</p>
      <p v-if="goods.afterSaleType" class="tag">{{goods.afterSaleType}}</p>
      <ul class="other-attr">
        <li>快递：{{goods.shipFee}}</li>
        <li>月销：{{goods.monthSales}}笔</li>
        <li>{{goods.provinceAndCity}}</li>
      </ul>
    </div>
    <!--已选/送至-->
    <div class="row-select-group">
      <div @click="buyModalVisible=true" class="row-select">
        <div class="detail-left">
          <p class="name">已选</p>
          <p class="title">{{goods.defaultColorName}}&ensp;{{goods.defaultSpecsName}}&ensp;{{form.num}}</p>
        </div>
        <i class='iconfont icon-arrow-right'></i>
      </div>
      <div @click="openAddressModal" class="row-select">
        <div class="detail-left">
          <div class="name">送至</div>
          <div class="title">{{goods.defaultAddress}}</div>
        </div>
        <i class='iconfont icon-arrow-right'></i>
      </div>
    </div>
    <!--详情-->
    <div id="Details" class="goods-details" v-html="goods.productDtl">

    </div>
    <!--评价-->
    <div id="Evaluation" class="evaluation">
      <template v-if="goods.EvalList.length">
        <div class="top-head">
          <p class="title">评价（{{goods.productEvalTotal}}）</p>
          <router-link tag="div" :to="{path:`/commit?id=${goods.productId}`}" class="all">
            <span>查看全部</span>
            <i class='iconfont icon-arrow-right'></i>
          </router-link>
        </div>
        <ul class="tag-list">
          <li v-for="(item,index) in goods.productEvalTagList" :key="index">
            {{item.EvalTagName}}&ensp;{{item.EvaltagNums}}
          </li>
        </ul>
        <ul class="detail-list">
          <li v-for="(item,index) in goods.EvalList" :key="index">
            <div class="user-info">
              <div class="detail">
                <div class="icon-wrap">
                  <img v-lazy="item.headImgurl" alt="">
                </div>
                <p class="nickname">{{item.memberName}}</p>
              </div>
              <!--evalStars-->
              <div class="start">
                <i v-for="i in item.evalStars" class="icon-pingjia iconfont"></i>
              </div>
            </div>
            <div class="content">{{item.evalDesc}}</div>
            <div class="pic-list">
              <div @click="setPreviewEvaluation(pic.picUrl)" class="icon-wrap" v-for="pic in item.evalPicList">
                <img v-lazy="pic.picUrl">
              </div>
            </div>

          </li>
        </ul>
      </template>
      <p v-else class="none-data">暂无更多评价，做第一个人吧～</p>
    </div>
    <!--底部固定按钮选项-->
    <div class="fixed-buy-footer">
      <div class="action-item">
        <i class="iconfont icon-kefu"></i>
        <p @click="$kefu({type:'product',params:customerServiceParams})">联系客服</p>
      </div>
      <div @click="buyModalVisible=true" class="action-item">
        <i class="iconfont icon-gouwuche"></i>
        <p>加入购物车</p>
      </div>
      <div @click="buyModalVisible=true" class="buy-btn">立即购买</div>
    </div>
    <!--商品图片幻灯片预览(头部/立即购买的浮层)-->
    <van-image-preview
      :startPosition="previewProduct.startPosition"
      v-model="previewProduct.visible"
      :images="previewProduct.list">
    </van-image-preview>
    <!--评论图片预览-->
    <van-image-preview
      :startPosition="previewEvaluation.startPosition"
      v-model="previewEvaluation.visible"
      :images="previewEvaluation.list">
    </van-image-preview>
    <!--立即购物浮层-->
    <van-popup v-model="buyModalVisible" position="bottom">
      <div class="select-modal">
        <i @click="buyModalVisible=false" class="iconfont icon-guanbi close-icon"></i>
        <div class="product-head">
          <div @click="openPreviewProduct(buySelectForm.goodsIcon)" class="icon-wrap">
            <img v-lazy="buySelectForm.goodsIcon">
          </div>
          <div class="detail">
            <p class="price">&#165; <span class="size">{{buySelectForm.price}}</span></p>
            <p class="name">货号：{{goods.goodsNo}}</p>
          </div>
        </div>
        <div class="detail-content">
          <div class="attr-group">
            <p class="title">颜色</p>
            <ul class="option-list">
              <li :class="{'is-selected':item.colorId===buySelectForm.colorId}"
                  @click="fetchSelectAttr('colorId',item)" :key="item.colorId"
                  v-for="item in goods.productColorList">
                {{item.colorName}}
              </li>
            </ul>
          </div>
          <div class="attr-group">
            <p class="title">规格/车型</p>
            <ul class="option-list">
              <li :class="{'is-selected':item.specsId===buySelectForm.specsId}"
                  @click="fetchSelectAttr('specsId',item)" :key="item.specsId"
                  v-for="item in goods.productSpecsList">{{item.specsName}}
              </li>
            </ul>
          </div>
        </div>
        <div class="fixed-group">
          <div class="num-select">
            <p class="title">数量</p>
            <div class="calc-wrap">
              <i
                @click="()=>buySelectForm.buyNums === 1 ? this.$toast({message: '不能减少了哟', duration: 600}):buySelectForm.buyNums -= 1"
                class="iconfont icon-jianhao1"></i>
              <span class="num">{{buySelectForm.buyNums}}</span>
              <i @click="buySelectForm.buyNums+=1" class="iconfont icon-jiahao"></i>
            </div>
          </div>
          <div class="btn-group">
            <div @click="addCart" class="btn-action">添加购物车</div>
            <div @click="getNowBuy()"
                 class="btn-action buy-btn">立即购买
            </div>
          </div>
        </div>
      </div>
    </van-popup>
    <!--地址浮层-->
    <van-popup v-model="addressModalVisible" position="bottom">
      <div class="address-modal">
        <div :class="{'is-selected':(selectAddress.addrId===v.addrId) || (v.isDefault && !selectAddress.addrId)}"
             class="address-row" v-for="(v,i) in addrList" :key="v.addrId">
          <div class="addressItem flex a-center">
            <div class="fx1" @click="changeAddress(v)">
              <div class="title flex a-center">
                <h3>{{v.contactsName}}</h3><span>{{v.phone}}</span>
              </div>
              <div class="addressmsg">
                <b v-if="v.isDefault">默认</b>
                {{v.dtlAddr}}
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>

  import './scss/goods.detail.scss'
  import page from '../../mixins/page'
  import {pullRefresh} from '../../mixins/pull.refresh'
  import pageScroll from '../../mixins/save.page.scroll'
  import geolocation from '../../util/geolocation'
  import user from '../../util/user'
  import {axiosCancelResInterceptors} from "../../util/service";

  let detailsEl, evaluationEl, HeadTopEl, pageEl, HeadSwiperEl;
  export default {
    mixins: [page, pullRefresh, pageScroll],
    name: 'GoodsDetail',
    data() {
      return {
        addressModalVisible: false,
        buyModalVisible: false,
        buySelectForm: {
          productId: '',
          goodsIcon: 0,
          colorId: 0,
          specsId: 0,
          buyNums: 1,
          price: 0,
          from: 'goodsDtl'
        },
        headSwipeIndex: 0,
        goodsVideo: {
          playing: false,
          url: ''
        },
        form: {
          num: 1,
          address: ''
        },
        goods: {
          "productId": 0,
          "price": 0,
          "goodsNo": '',
          "productDesc": "",
          "defaultAddress": "",
          "provinceAndCity": "",
          "monthSales": 0,
          "shipFee": 0,
          "defaultColorId": 0,
          "defaultColorName": "",
          "defaultSpecsId": 0,
          "defaultSpecsName": "",
          "productPicList": [],
          "productColorList": [],
          "productSpecsList": [],
          "productEvalTotal": 0,
          "productName": "",
          "productEvalTagList": [],
          "EvalList": []
        },
        topAttrName: '',
        previewProduct: {
          list: [],
          startPosition: 0,
          visible: false
        },
        previewEvaluation: {
          list: [],
          startPosition: 0,
          visible: false,
        },
        PAGE_QUERY: {},
        addrList: null,
        selectAddress: {},
      }
    },
    computed: {
      // 联系客服参数
      customerServiceParams() {
        if (!this.goods.productName) return null;
        return {
          productName: this.goods.productName,
          productDesc: this.goods.productDesc,
          goodsIcon: this.buySelectForm.goodsIcon,
          goodsNo: this.goods.goodsNo
        }
      }
    },
    created() {
      window.scrollTo(0, 0);
    },
    mounted() {
      HeadTopEl = document.getElementById('HeadTop');
      pageEl = document.getElementById('Page');
      detailsEl = document.getElementById('Details');
      evaluationEl = document.getElementById('Evaluation');
      HeadSwiperEl = document.getElementById('HeadSwiper');
      window.addEventListener('scroll', this.bindPageScroll, false);
    },
    beforeRouteEnter(to, from, next) {
      next(vm => {
        window.addEventListener('scroll', vm.bindPageScroll, false);
        if (vm.isEnableRefreshStatus || to.query.productId != vm.goods.productId) {
          window.scrollTo(0, 0);
          vm.goods = {
            "productId": 0,
            "price": 0,
            "goodsNo": '',
            "productDesc": "",
            "defaultAddress": "",
            "monthSales": 0,
            "shipFee": 0,
            "defaultColorId": 0,
            "defaultColorName": "",
            "defaultSpecsId": 0,
            "defaultSpecsName": "",
            "productPicList": [],
            "productColorList": [],
            "productSpecsList": [],
            "productEvalTotal": 0,
            "productName": "",
            "productEvalTagList": [],
            "EvalList": []
          };
          vm.selectAddress = {};
          vm.addrList = null;
          vm.PAGE_QUERY = to.query;
          vm.forceRefresh();
        } else if (vm.goods.productId) {
          vm.isPageLoad = true;
        }
      })
    },
    beforeRouteLeave(to, from, next) {
      window.removeEventListener('scroll', this.bindPageScroll);
      next(true);
      this.isEnableRefreshStatus = to.path.indexOf('/order') === -1;
      this.isPageLoad = false;
    },
    methods: {
			back(){
				this.$store.commit('setBackstate',true)
				this.$router.go(-1)
			},
      // 图片幻灯片地址预览
      openPreviewProduct(url){
        this.previewProduct.startPosition=this.previewProduct.list.findIndex(item=>item===url);
        this.previewProduct.visible=true
      },
      // 打开地址请求弹窗
      openAddressModal() {
        if (this.addrList) {
          this.addressModalVisible = true;
          return;
        }
        this.$loading.open();
        this.$ajax.getAddrList().then(res => {
          this.$loading.close();
          if (res.code == 0) {
            this.addrList = res.data.addrList;
            this.addressModalVisible = true;
          }
        })
      },
      // 根据地址获取运费
      changeAddress(item) {
        this.$loading.open();
        this.$ajax.getShipFeeByArea({area: item.area, productId: this.goods.productId}).then(res => {
          this.$loading.close();
          let {provinceAndCity, shipFee} = res.data;
          this.goods.provinceAndCity = provinceAndCity;
          this.goods.defaultAddress = item.dtlAddr;
          this.goods.shipFee = shipFee;
          this.selectAddress = item;
          this.addressModalVisible = false;
        })
      },
      // 地址请求
      fetchAddress() {
        axiosCancelResInterceptors().post('/api/member/getAddrList').then(res => {
          if (res.code == 0) {
            let addrList = res.data.addrList;
            this.addrList = addrList;
            this.selectAddress = addrList.find(item => item.isDefault);
            if(this.selectAddress){
              this.goods.defaultAddress = this.selectAddress.dtlAddr;
              this.goods.provinceAndCity = this.selectAddress.provinceAndCity
            }
          }
        })
      },
      // 顶部tab切换
      topScrollAttr(selectorEl) {
        this.topAttrName = selectorEl;
        if (!selectorEl) return window.scrollTo(0, 0);
        let top = document.getElementById(selectorEl).getBoundingClientRect().top;
        let topHeight = HeadTopEl.clientHeight;
        let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        window.scrollTo(0, scrollTop + top - topHeight);
      },
      // 弹窗中的立即购买
      getNowBuy() {
        if (!user.isSign()) {
          this.$router.push({
            path: '/login', query: {
              redirect: this.$route.path,
              from: this.$route.path,
            }
          });
        }/* else if (!this.selectAddress || !this.selectAddress.addrId) {
          this.$toast({message: '请选择地址', duration: 1000, type: 'fail'});
        }*/ else {
          let params = {...this.buySelectForm};
          if(this.selectAddress){
            params['addrId'] = this.selectAddress.addrId;
          }
          delete params.goodsIcon;
          this.$router.push({path: '/order', query: params});
        }
      },
      // 获取不同属性组合的价格
      fetchSelectAttr(key, item) {
        if (this.buySelectForm[key] === item[key]) return;
        this.$loading.open();
        let params = {
          productId: this.goods.productId,
          colorId: this.buySelectForm.colorId,
          specsId: this.buySelectForm.specsId,
          [key]: item[key]
        };
        this.$ajax.getProductPrice(params).then(
          res => {
            this.buySelectForm.price = res.data.price;
            this.buySelectForm.goodsIcon = (this.goods.productPicList.find(item => item.colorId === params.colorId) || this.goods.productPicList[0]).picUrl;
            this.buySelectForm.colorId = params.colorId;
            this.buySelectForm.specsId = params.specsId;
            let defaultKey = {
              colorId: {
                id: 'defaultColorId',
                attr: 'colorName',
                name: 'defaultColorName'
              },
              specsId: {
                id: 'defaultSpecsId',
                attr: 'specsName',
                name: 'defaultSpecsName'
              }
            }[key];
            this.goods[defaultKey.id] = item[key];
            this.goods[defaultKey.name] = item[defaultKey.attr];
            this.$loading.close();
          },
          () => {
            this.$loading.close();
          }
        )
      },
      // 添加购物车
      addCart() {
        this.$loading.open();
        this.$ajax.setShopCarList({
          ...this.buySelectForm,
          productId: this.goods.productId,
        }).then(
          res => {
            this.buyModalVisible = false;
            this.$loading.close();
            this.$toast({message: '添加成功', duration: 1000, type: 'success'});
          },
          () => {
            this.$loading.close();
          }
        )
      },
      // 播放视频
      playVideo(status, item) {
        if (item) {
          this.goodsVideo.url = item.videoUrl;
        }
        const stop = status === 0;
        let playing = this.goodsVideo.playing;
        if (stop || playing) {
          const videoEl = document.getElementById('GoodsVideo');
          videoEl.pause();
          if (stop) {
            videoEl.currentTime = 0;
          }
          this.goodsVideo.playing = false;
        } else {
          this.goodsVideo.playing = true;
          this.$nextTick(function () {
            const videoEl = document.getElementById('GoodsVideo');
            videoEl.play();
          })
        }
      },
      // 展示评论的图片
      setPreviewEvaluation(url) {
        this.previewEvaluation.startPosition = this.previewEvaluation.list.findIndex(item => item === url);
        this.previewEvaluation.visible = true;
      },
      // 绑定头部滚动效果
      bindPageScroll() {
        if (!HeadTopEl || !HeadSwiperEl) return;
        let detailElTop = detailsEl.getBoundingClientRect().top;
        let swiperTop = evaluationEl.getBoundingClientRect().top;
        let evaluationTop = evaluationEl.getBoundingClientRect().top;
        let topHeadHeight = HeadTopEl.clientHeight;
        let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        //浏览器视口的高度
        let windowClientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        //文档的总高度
        let documentScrollHeight = document.body.scrollHeight || document.documentElement.scrollHeight;

        let reaming = HeadSwiperEl.clientHeight - topHeadHeight;
        let isBottom = scrollTop + windowClientHeight >= (documentScrollHeight - 20);
        if (scrollTop > reaming) {
          pageEl.classList.add('is-fixed-float');
        } else {
          pageEl.classList.remove('is-fixed-float');
        }
        if (detailElTop <= topHeadHeight) {
          this.topAttrName = 'Details'
        }
        if ((evaluationTop <= topHeadHeight) || isBottom) {
          this.topAttrName = 'Evaluation'
        }
        if (scrollTop < topHeadHeight) {
          this.topAttrName = ''
        }
      },
      // 设置gps
      setGeolocation() {
        /*h5版本*/
        geolocation().then(coords => {
          this.$ajax.getShipFeeByBaiDu({
            productId: this.goods.productId,
            lat: coords.latitude,
            lng: coords.longitude
          }).then(res => {
            this.goods.shipFee = res.data.provinceAndCity.shipFee;
            this.goods.provinceAndCity = res.data.provinceAndCity;
          });
        })

        // (plus)版本扩展API加载完毕后调用onPlusReady回调函数
        // document.addEventListener('plusready', () => {
        //   plus.geolocation.getCurrentPosition(gps => {
        //     this.$ajax.getShipFeeByBaiDu({
        //       lat: gps.coords.latitude,
        //       lng: gps.coords.longitude
        //     }).then(res => {
        //       this.goods.shipFee = res.data.provinceAndCity.shipFee
        //       this.goods.defaultAddress = res.data.provinceAndCity
        //     });
        //   }, function (e) {
        //     // 获取gps定位失败
        //     console.warn('Geolocation error: ' + e.message);
        //   });
        // }, false);
      },
      // 页面初始化
      fetchPage() {
        this.$ajax.getProductInfo({productId: this.PAGE_QUERY.productId}).then(
          res => {
            this.goods = res.data;
            this.goods.provinceAndCity=res.data.defaultAddress;
            this.previewProduct.list = this.goods.productPicList.map(item => item.picUrl);
            this.previewEvaluation.list = this.goods.EvalList.map(item => item.evalPicList).map(item => item.picUrl);
            // 评论连续预览图像
            let evalListImgs = [];
            this.goods.EvalList.map(item => item.evalPicList).forEach(item => {
              evalListImgs = evalListImgs.concat(item.map(item => item.picUrl))
            });
            this.previewEvaluation.list = evalListImgs;
            let {
              defaultColorId: colorId,
              defaultSpecsId: specsId,
              productId,
              price
            } = this.goods;
            this.buySelectForm = {
              ...this.buySelectForm,
              colorId,
              specsId,
              price,
              productId,
              goodsIcon: (this.goods.productPicList.find(item => item.colorId === colorId) || this.goods.productPicList[0]).picUrl
            };
            this.loadEnd();
            this.setGeolocation();
            this.fetchAddress();
            setTimeout(() => {
              window.scrollTo(0, 0);
            }, 50);
          },
          err => {
            this.loadEnd();
          }
        )
      },
    }
  }
</script>
